<template>
  <section class="flex justify-between bg-white mb-12 py-6">
    <aside>
      <el-image class="w-[690px] h-[428px]" :src="typeInfo.img" />
      <p class="ml-14 text-gray-400">*图片仅供参考,车辆配置以描述为准。</p>
    </aside>
    <aside>
      <h3 class="font-bold text-xl text-stone-900">{{ typeInfo.carName }}</h3>
      <div class="my-2 mb-5">
        <el-button>免购置税</el-button>
        <el-button>提供发票</el-button>
        <el-button>期满过户</el-button>
      </div>
      <ul>
        <li class="item">
          <span class="itemName">地区选择</span>
          <el-cascader
            size="large"
            :props="{ expandTrigger: 'hover' }"
            :options="provinceAndCityData"
            v-model="selectedOptions"
            @change="handleChange"
          />
        </li>
        <li class="item">
          <span class="itemName">门店选择</span>
          <el-select v-model="carShopValue" :placeholder="placeholder" :disabled="!carShopList.length">
            <el-option
              v-for="(item, index) in carShopList"
              :key="item._id"
              :label="item.shopName"
              :value="item._id"
              @click.native="carShopIndex = index"
            />
          </el-select>
        </li>
        <li class="item">
          <span class="itemName">租赁日期</span>
          <el-date-picker
            v-model="date"
            type="datetimerange"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="right"
          />
        </li>
        <li class="item">
          <span class="itemName">付款方式</span>
          <el-button class="active">灵活分期</el-button>
        </li>
      </ul>
      <p class="my-5 text-sm text-[#333]">分期方案</p>
      <el-descriptions class="mb-5" direction="vertical" :column="2" border>
        <el-descriptions-item label="首付">0元</el-descriptions-item>
        <el-descriptions-item label="日租金">{{ typeInfo.rent }}元</el-descriptions-item>
      </el-descriptions>
      <el-button type="primary" @click="open" :disabled="!date.length">购买</el-button>
    </aside>
  </section>
</template>

<script>
  import { provinceAndCityData, CodeToText } from 'element-china-area-data'
  import QRCode from 'qrcode'

  export default {
    name: 'ParamSelect',
    data() {
      return {
        // 区域码转汉字
        CodeToText,
        // 数据源
        provinceAndCityData,
        //  选择的省份城市
        selectedOptions: ['110000', '110100'],
        // 选择的门店
        carShopValue: '',
        // 选择的门店索引
        carShopIndex: 0,
        pickerOptions: {
          shortcuts: [
            {
              text: '最近一周',
              onClick(picker) {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
                picker.$emit('pick', [start, end])
              },
            },
            {
              text: '最近一个月',
              onClick(picker) {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
                picker.$emit('pick', [start, end])
              },
            },
            {
              text: '最近三个月',
              onClick(picker) {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
                picker.$emit('pick', [start, end])
              },
            },
          ],
        },
        date: [],
      }
    },
    mounted() {
      this.getShopByAddress({
        province: this.selectedOptions[0],
        city: this.selectedOptions[1],
        type_id: this.type_id,
      })
    },
    methods: {
      ...mapActions('shop', ['getShopByAddress']),
      ...mapActions('order', ['reqOrder']),
      handleChange(value) {
        // <div>区域码转汉字：{{ CodeToText[selectedOptions[0]] }},{{ CodeToText[selectedOptions[1]] }}</div>
        this.selectedOptions = value
        this.getShopByAddress({
          province: this.selectedOptions[0],
          city: this.selectedOptions[1],
          type_id: this.type_id,
        })
      },
      // 提交订单
      async submitOrder() {
        if (!this.token) return this.$router.push(`/login?redirect=${this.$route.path}`)
        let data = {
          rent: this.typeInfo.rent,
          start: this.date[0].getTime(),
          end: this.date[1].getTime(),
          car: this.carShopList[this.carShopIndex]?.carList[0]?._id,
          shop: this.carShopValue,
        }
        try {
          await this.reqOrder(data)
          this.$message.success('交易成功')
        } catch (error) {
          this.$message.error('交易失败')
        }
      },
      // 打开支付弹窗
      async open() {
        let imgUrl = await QRCode.toDataURL('weixin://wxpay/bizpayurl?pr=K9wXUn5zz')
        this.$alert(
          `<p class="text-lg">您需要支付<span class="text-primary"> ${this.payNum} </span>元</p><img src=${imgUrl} />`,
          '微信支付',
          {
            // 确定按钮的文本内容
            confirmButtonText: '支付成功',
            // 取消按钮
            showCancelButton: true,
            // 取消按钮文本
            cancelButtonText: '支付遇到问题',
            // 支持html片段
            dangerouslyUseHTMLString: true,
            // 居中
            center: true,
            // done 用于关闭 MessageBox 实例
            beforeClose: (action, instance, done) => {
              // 取消按钮
              if (action == 'cancel') {
                done()
              } else {
                this.submitOrder()
                done()
              }
            },
          },
        ).catch(() => {})
      },
    },
    computed: {
      ...mapState('type', ['typeInfo']),
      ...mapState('shop', ['carShopList']),
      ...mapState('user', ['token']),
      type_id() {
        return this.$route.params.typeId
      },
      placeholder() {
        return this.carShopList.length ? '请选择门店' : '当前地区没有该车可租借'
      },
      payNum() {
        return ((this.date[1].getTime() - this.date[0].getTime()) / 1000 / 3600 / 24) * this.typeInfo.rent
      },
    },
  }
</script>

<style lang="scss" scoped>
  .item {
    font-size: 14px;
    color: #333;

    .itemName {
      display: inline-block;
      width: 80px;
    }

    &:not(:last-child) {
      margin-bottom: 10px;
    }
  }

  .active {
    color: #1cc200;
    border-color: #bbedb3;
    background-color: #e8f9e6;
  }
</style>
